﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using QunProject.Common;
using System.Web;
using QunProject.Model;
using Newtonsoft.Json;
using EnumHelper = QunProject.Model.EnumHelper;

namespace QunProject.Interface
{
    public class Server : BaseInterface, IServer
    {
        public Result UserLoginOut()
        {
            Cache.Clear(ToKen);
            return Result.Success();
        }

        public Result GetTestArticlePassResult(int articleId)
        {
            var article = EF.article.SingleOrDefault(x => x.ID == articleId && x.IsValid.Value);
            if (article == null)
                return Result.Fail("文章错误");

            if (IsLogin())
            {
                if (LoginMember.ID == article.MemberID)
                {
                    return Result.Success(false);
                }
            }

            var data = !string.IsNullOrWhiteSpace(article.Password) ? true : false;
            return Result.Success(data);
        }

        public Result GetMemberReplyListResult(int page = 1, int limit = 10)
        {
            List<long> articleIds = new List<long>();
            List<long> childIds = new List<long>();
            List<long> parentIds = new List<long>();
            var memberReplyList = EF.reply.Where(x => x.MemberID == LoginMember.ID).OrderByDescending(x => x.CreateTime);
            int count = memberReplyList.Count();
            var list = memberReplyList.Skip((page - 1) * limit).Take(limit).ToList();
            list.ForEach(x =>
            {
                articleIds.Add(x.ArticleID.Value);
                childIds.Add(x.ID);
                parentIds.Add(x.ParentID.Value);
            });
            // 对文章的回复
            var articleList = EF.article.Where(x => articleIds.Contains(x.ID)).ToList();
            // 其他用户对当前用户的回复
            var childList = EF.reply.Where(x => childIds.Contains(x.ParentID.Value)).ToList();
            // 当前用户对其他用户的回复
            var parentList = EF.reply.Where(x => parentIds.Contains(x.ID)).ToList();
            // 所有用户
            var memberList = EF.member.Where(x => true).ToList();

            var data = list.Select(x => new
            {
                x.ID,
                CreateTime = x.CreateTime.Value.ToString("yyyy-MM-dd hh:mm:ss"),
                x.Remark,
                x.ParentID,
                x.MemberID,
                x.Content,
                x.Praise,
                x.Criticism,
                x.ArticleID,
                x.IsDisplay,
                Article = new Func<object>(() =>
                {
                    if (x.ParentID == 0)
                    {
                        var _article = articleList.SingleOrDefault(c => c.ID == x.ArticleID);
                        return new
                        {
                            _article.ID,
                            CreateTime = _article.CreateTime.Value.ToString("yyyy-MM-dd hh:mm:ss"),
                            _article.Title,
                        };
                    }
                    else
                        return null;
                }).Invoke(),
                Child = new Func<object>(() =>
                {
                    var _childs = childList.Where(c => c.ParentID == x.ID).Select(c => new
                    {
                        c.ID,
                        CreateTime = c.CreateTime.Value.ToString("yyyy-MM-dd hh:mm:ss"),
                        c.Content,
                        Member = new Func<object>(() =>
                        {
                            var _member = memberList.SingleOrDefault(v => v.ID == c.MemberID);
                            return new
                            {
                                _member.Name,
                                _member.ID,
                                _member.Number
                            };
                        }).Invoke()
                    });
                    return _childs;
                }).Invoke(),
                Parent = new Func<object>(() =>
                {
                    if (x.ParentID > 0)
                    {
                        var _reply = parentList.SingleOrDefault(c => c.ID == x.ParentID);
                        return new
                        {
                            _reply.ID,
                            CreateTime = _reply.CreateTime.Value.ToString("yyyy-MM-dd hh:mm:ss"),
                            _reply.Content,
                            Member = new Func<object>(() =>
                            {
                                var _member = memberList.SingleOrDefault(v => v.ID == _reply.MemberID);
                                return new
                                {
                                    _member.Name,
                                    _member.ID,
                                    _member.Number
                                };
                            }).Invoke()
                        };
                    }
                    else
                        return null;
                }).Invoke(),
            });

            return Result.SuccessReturnData(count, data);
        }

        public Result EditComplainResult(int type, int objId, string content)
        {
            if (type == (int)EnumHelper.ComplainType.文章)
            {
                var article = EF.article.SingleOrDefault(x => x.ID == objId);
                if (article == null)
                    return Result.Fail("文章错误");

                var model = new complain()
                {
                    Content = content,
                    CreateTime = DateTime.Now,
                    ObjectID = objId,
                    Processing = (int)EnumHelper.Processing.等待处理,
                    ObjectType = (int)EnumHelper.ComplainType.文章
                };
                EF.complain.Add(model);
                bool isOk = EF.SaveChanges() > 0;
                return isOk ? Result.Success() : Result.Fail();
            }
            else if (type == (int)EnumHelper.ComplainType.评论)
            {
                var reply = EF.reply.SingleOrDefault(x => x.ID == objId);
                if (reply == null)
                    return Result.Fail("文章错误");

                var model = new complain()
                {
                    Content = content,
                    CreateTime = DateTime.Now,
                    ObjectID = objId,
                    Processing = (int)EnumHelper.Processing.等待处理,
                    ObjectType = (int)EnumHelper.ComplainType.评论
                };
                EF.complain.Add(model);
                bool isOk = EF.SaveChanges() > 0;
                return isOk ? Result.Success() : Result.Fail();
            }
            else
            {
                return Result.Fail("无效的投诉");
            }
        }

        public Result GetReplyListResult(int articleId, int page = 1, int limit = 10, int sort = 0)
        {
            var article = EF.article.SingleOrDefault(x => x.ID == articleId && x.IsValid.Value);
            if (article == null)
                return Result.Fail("文章错误");

            var replyAll = EF.reply.Where(x => x.ArticleID == articleId && x.IsDisplay.Value);
            var list = new List<reply>();
            if (sort == 0)
            {
                list = replyAll.OrderByDescending(x => x.CreateTime).Skip((page - 1) * limit).Take(limit).ToList();
            }
            else
            {
                list = replyAll.OrderByDescending(x => x.CreateTime).OrderByDescending(x => x.Praise).Skip((page - 1) * limit).Take(limit).ToList();
            }
            var memberAll = EF.member.Where(x => true);

            var data = list.Select(x => new
            {
                x.ID,
                CreateTime = x.CreateTime.Value.ToString("yyyy-MM-dd hh:mm:ss"),
                x.Remark,
                x.ParentID,
                x.MemberID,
                x.Content,
                x.Praise,
                x.Criticism,
                x.ArticleID,
                Member = new Func<object>(() =>
                {
                    member _member = memberAll.SingleOrDefault(c => c.ID == x.MemberID);
                    if (_member != null)
                    {
                        return new
                        {
                            _member.Name,
                            _member.Number,
                            _member.Img,
                            _member.Identity,
                            _member.IsProve
                        };
                    }
                    return _member;
                }).Invoke(),
                Childs = new Func<object>(() =>
                {
                    return replyAll.Where(c => c.ParentID == x.ID).ToList().Select(c => new
                    {
                        c.ID,
                        CreateTime = c.CreateTime.Value.ToString("yyyy-MM-dd hh:mm:ss"),
                        c.Remark,
                        c.ParentID,
                        c.MemberID,
                        c.Content,
                        c.Praise,
                        c.Criticism,
                        c.ArticleID,
                        Member = new Func<object>(() =>
                        {
                            member _member = memberAll.SingleOrDefault(v => v.ID == c.MemberID);
                            if (_member != null)
                            {
                                return new
                                {
                                    _member.Name,
                                    _member.Number,
                                    _member.Img,
                                    _member.Identity,
                                    _member.IsProve
                                };
                            }
                            return _member;
                        }).Invoke(),
                    });
                }).Invoke()
            });

            return Result.SuccessReturnData(replyAll.Count(), data);
        }

        public Result EditReplyPraiseCriticismResult(int type, int replyId)
        {
            var model = EF.reply.SingleOrDefault(x => x.ID == replyId && x.IsDisplay.Value);
            if (model == null)
                return Result.Fail("回复错误");

            model = EF.reply.Attach(model);
            if (type == 1)
            {
                model.Praise += 1;
            }
            else
            {
                model.Criticism += 1;
            }

            bool isOk = EF.SaveChanges() > 0;
            return isOk ? Result.Success() : Result.Fail();
        }

        public Result EditReplyResult(int articleId, int? replyId, string content)
        {
            var article = EF.article.SingleOrDefault(x => x.ID == articleId && x.IsValid.Value);
            if (article == null)
                return Result.Fail("文章错误");
            if (!article.IsReply.Value)
                return Result.Fail("本文章不允许回复");

            var model = new reply()
            {
                ArticleID = articleId,
                CreateTime = DateTime.Now,
                Criticism = 0,
                IsDisplay = true,
                Praise = 0,
                ParentID = 0,
                MemberID = LoginMember.ID,
                Content = content
            };

            if (replyId.HasValue)
            {
                var reply = EF.article.SingleOrDefault(x => x.ID == articleId && x.IsValid.Value);
                if (reply == null)
                    return Result.Fail("回复错误");

                model.ParentID = replyId;
            }

            EF.reply.Add(model);
            bool isOk = EF.SaveChanges() > 0;
            return isOk ? Result.Success() : Result.Fail();
        }

        public Result EditArticlePraiseCriticismResult(int type, int articleId)
        {
            var model = EF.article.SingleOrDefault(x => x.ID == articleId && x.IsValid.Value);
            if (model == null)
                return Result.Fail("文章错误");

            model = EF.article.Attach(model);
            if (type == 1)
            {
                model.Praise += 1;
            }
            else
            {
                model.Criticism += 1;
            }

            bool isOk = EF.SaveChanges() > 0;
            return isOk ? Result.Success() : Result.Fail();
        }

        public Result DeleteMemberSpecialResult(int specialId)
        {
            var model = EF.special.SingleOrDefault(x => x.ID == specialId);
            if (model == null)
                return Result.Fail("文章错误");
            if (model.MemberID != MemberID)
                return Result.Fail("权限不足");

            var isOk = false;
            var msg = "执行失败";
            using (var context = new Model.QunProjectEntities())
            {
                using (var dbContextTransaction = context.Database.BeginTransaction())
                {
                    try
                    {
                        model = context.special.Attach(model);
                        model.IsValid = false;
                        context.Database.ExecuteSqlCommand("update article set IsValid = false where SpecialID = @SpecialID", new MySql.Data.MySqlClient.MySqlParameter("@SpecialID", model.ID));
                        context.SaveChanges();
                        dbContextTransaction.Commit();
                        isOk = true;
                    }
                    catch (Exception e)
                    {
                        dbContextTransaction.Rollback();
                        msg = e.Message;
                        isOk = false;
                    }
                }
            }

            return isOk ? Result.Success() : Result.Fail(msg);
        }

        public Result DeleteMemberArticleResult(int articleId)
        {
            var model = EF.article.SingleOrDefault(x => x.ID == articleId);
            if (model == null)
                return Result.Fail("文章错误");
            if (model.MemberID != MemberID)
                return Result.Fail("权限不足");

            model = EF.article.Attach(model);
            model.IsValid = false;
            var isOk = EF.SaveChanges() > 0;

            return isOk ? Result.Success() : Result.Fail();
        }

        public Result GetMemberSpecialArticleResult(int specialId, int page = 1, int limit = 10)
        {
            var list = (from a in EF.article
                        join m in EF.member on a.MemberID equals m.ID
                        where a.Types == (int)EnumHelper.ArticleType.普通文章 && a.IsValid.Value && a.MemberID == MemberID && a.SpecialID == specialId
                        orderby a.CreateTime descending
                        select new
                        {
                            a.ID,
                            a.CreateTime,
                            a.Title,
                            a.MemberID,
                            a.Audit,
                            a.AuditReason,
                            a.ClickAmount,
                            a.Password,
                            a.Img,
                            a.Praise,
                            a.Content,
                            a.Criticism,
                            a.Tops,
                            a.IsReply,
                            a.Types,
                            a.ClassifyID,
                            a.SpecialID,
                            a.Sort,
                            UserName = m.Name
                        });

            List<classify> classifyList = EF.classify.Where(x => true).ToList();

            var data = list.Skip((page - 1) * limit).Take(limit).ToList().Select(x => new
            {
                x.ID,
                CreateTime = x.CreateTime.Value.ToString("yyyy-MM-dd hh:mm:ss"),
                x.Title,
                x.MemberID,
                x.ClickAmount,
                x.Img,
                x.Praise,
                Content = HttpHelper.ReplaceHtmlTag(x.Content, 72),
                x.Criticism,
                x.Tops,
                x.Audit,
                x.AuditReason,
                x.IsReply,
                x.Types,
                x.ClassifyID,
                x.SpecialID,
                x.Sort,
                x.UserName,
                ClassifyName = new Func<string>(() =>
                {
                    var _name = string.Empty;
                    var _classify = classifyList.SingleOrDefault(s => s.ID == x.ClassifyID);
                    if (_classify != null)
                    {
                        _name = _classify.Name;
                    }
                    return _name;
                }).Invoke()
            });
            return Result.SuccessReturnData(list.Count(), data);
        }

        public Result GetMemberArticleResult(int articleId)
        {
            var model = EF.article.SingleOrDefault(x => x.ID == articleId);
            if (model == null)
                return Result.Fail("文章错误");
            if (model.MemberID != MemberID)
                return Result.Fail("权限不足");

            var Resources = EF.resource.Where(x => x.ArticleID == model.ID);
            var data = new
            {
                model.ID,
                model.CreateTime,
                model.Remark,
                model.Title,
                model.Content,
                model.MemberID,
                model.Audit,
                model.AuditReason,
                model.Source,
                model.SourceUrl,
                model.ClickAmount,
                model.Password,
                model.Img,
                model.Praise,
                model.Criticism,
                model.Tops,
                model.IsReply,
                model.Types,
                model.ClassifyID,
                model.SpecialID,
                model.Sort,
                model.IsValid,
                Resources
            };
            return Result.Success(data);
        }

        public Result GetMemberSpecialResult(int specialId)
        {
            var model = EF.special.SingleOrDefault(x => x.ID == specialId);
            if (model == null)
                return Result.Fail("专题错误");
            if (model.MemberID != MemberID)
                return Result.Fail("权限不足");

            return Result.Success(model);
        }

        public Result GetMemberDiscussResult(int articleId)
        {
            var model = EF.article.SingleOrDefault(x => x.ID == articleId);
            if (model == null)
                return Result.Fail("讨论错误");
            if (model.MemberID != MemberID)
                return Result.Fail("权限不足");

            return Result.Success(model);
        }

        public Result UserEditDiscussResult(Model.article model)
        {
            model.Content = model.Content.UnicodeToString();
            //model.Content = model.Content.Replace("[ad]", "+");
            //model.Content = model.Content.Replace("[eq]", "=");
            //model.Content = HttpUtility.UrlDecode(model.Content);

            if (model.Title.IsNullOrWhiteSpace())
                return Result.Fail("讨论标题不能为空");
            if (model.Content.IsNullOrWhiteSpace())
                return Result.Fail("讨论内容不能为空");

            var _model = new article()
            {
                Audit = (int)EnumHelper.AuditType.待审核,
                AuditReason = string.Empty,
                ClassifyID = null,
                ClickAmount = 0,
                Content = string.Empty,
                CreateTime = DateTime.Now,
                Criticism = 0,
                Img = string.Empty,
                IsReply = true,
                Praise = 0,
                Password = string.Empty,
                Remark = string.Empty,
                MemberID = MemberID,
                Source = string.Empty,
                Sort = 1,
                SourceUrl = string.Empty,
                SpecialID = null,
                Title = string.Empty,
                IsValid = true,
                Tops = false,
                Types = (int)EnumHelper.ArticleType.技术讨论
            };

            if (model.ID > 0)
            {
                _model = EF.article.SingleOrDefault(x => x.ID == model.ID);
                if (_model == null)
                    return Result.Fail("讨论错误");
                if (_model.MemberID != MemberID)
                    return Result.Fail("权限不足");

                _model = EF.article.Attach(_model);
            }

            _model.Audit = (int)EnumHelper.AuditType.待审核;
            _model.AuditReason = string.Empty;
            _model.Content = model.Content;
            _model.Password = model.Password;
            _model.Remark = model.Remark;
            _model.Title = model.Title;

            if (LoginMember.IsProve.Value)
            {
                _model.Audit = (int)EnumHelper.AuditType.审核通过;
            }

            bool isSucc = false;
            if (model.ID > 0)
            {
                isSucc = EF.SaveChanges() > 0;
            }
            else
            {
                EF.article.Add(_model);
                isSucc = EF.SaveChanges() > 0;
            }
            return isSucc ? Result.Success() : Result.Fail();
        }

        public Result UserEditArticleDraftResult(Model.article model, string resJson = "")
        {
            model.Content = model.Content.UnicodeToString();
            //model.Content = model.Content.Replace("[ad]", "+");
            //model.Content = model.Content.Replace("[eq]", "=");
            //model.Content = HttpUtility.UrlDecode(model.Content);

            if (model.Title.IsNullOrWhiteSpace())
                return Result.Fail("文章标题不能为空");
            if (model.Content.IsNullOrWhiteSpace())
                return Result.Fail("文章内容不能为空");

            var _model = new article()
            {
                Audit = (int)EnumHelper.AuditType.草稿,
                AuditReason = string.Empty,
                ClassifyID = null,
                ClickAmount = 0,
                Content = string.Empty,
                CreateTime = DateTime.Now,
                Criticism = 0,
                Img = string.Empty,
                IsReply = true,
                IsValid = true,
                Praise = 0,
                Password = string.Empty,
                Remark = string.Empty,
                MemberID = MemberID,
                Source = string.Empty,
                Sort = 1,
                SourceUrl = string.Empty,
                SpecialID = null,
                Title = string.Empty,
                Tops = false,
                Types = (int)EnumHelper.ArticleType.普通文章
            };

            if (model.ID > 0)
            {
                _model = EF.article.SingleOrDefault(x => x.ID == model.ID);
                if (_model == null)
                    return Result.Fail("文章错误");
                if (_model.MemberID != MemberID)
                    return Result.Fail("权限不足");

                _model = EF.article.Attach(_model);
            }

            _model.Audit = (int)EnumHelper.AuditType.草稿;
            _model.AuditReason = string.Empty;
            _model.ClassifyID = model.ClassifyID;
            _model.Content = model.Content;
            _model.Img = model.Img;
            _model.IsReply = model.IsReply;
            _model.Password = model.Password;
            _model.Remark = model.Remark;
            _model.Source = model.Source;
            _model.SourceUrl = model.SourceUrl;
            _model.SpecialID = model.SpecialID;
            _model.Title = model.Title;

            bool isSucc = false;
            if (model.ID > 0)
            {
                isSucc = EF.SaveChanges() > 0;
            }
            else
            {
                EF.article.Add(_model);
                isSucc = EF.SaveChanges() > 0;
            }

            string msg = "执行失败";
            if (!string.IsNullOrWhiteSpace(resJson))
            {
                var resList = JsonConvert.DeserializeObject<List<resource>>(resJson);
                resList.ForEach(x =>
                {
                    x.CreateTime = DateTime.Now;
                    x.ArticleID = _model.ID;
                });

                using (var context = new Model.QunProjectEntities())
                {
                    using (var dbContextTransaction = context.Database.BeginTransaction())
                    {
                        try
                        {
                            context.Database.ExecuteSqlCommand("delete from resource where ArticleID = @ArticleID", new MySql.Data.MySqlClient.MySqlParameter("@ArticleID", model.ID));
                            context.resource.AddRange(resList);
                            context.SaveChanges();
                            dbContextTransaction.Commit();
                            isSucc = true;
                        }
                        catch (Exception e)
                        {
                            dbContextTransaction.Rollback();
                            msg = e.Message;
                            isSucc = false;
                        }
                    }
                }
            }

            return isSucc ? Result.Success(_model.ID) : Result.Fail(msg);
        }

        public Result UserEditArticleResult(Model.article model, string resJson = "")
        {
            model.Content = model.Content.UnicodeToString();
            //model.Content = model.Content.Replace("[ad]", "+");
            //model.Content = model.Content.Replace("[eq]", "=");
            //model.Content = HttpUtility.UrlDecode(model.Content);

            if (model.Title.IsNullOrWhiteSpace())
                return Result.Fail("文章标题不能为空");
            if (model.Content.IsNullOrWhiteSpace())
                return Result.Fail("文章内容不能为空");

            var _model = new article()
            {
                Audit = (int)EnumHelper.AuditType.待审核,
                AuditReason = string.Empty,
                ClassifyID = null,
                ClickAmount = 0,
                Content = string.Empty,
                CreateTime = DateTime.Now,
                Criticism = 0,
                Img = string.Empty,
                IsReply = true,
                IsValid = true,
                Praise = 0,
                Password = string.Empty,
                Remark = string.Empty,
                MemberID = MemberID,
                Source = string.Empty,
                Sort = 1,
                SourceUrl = string.Empty,
                SpecialID = null,
                Title = string.Empty,
                Tops = false,
                Types = (int)EnumHelper.ArticleType.普通文章
            };

            if (model.ID > 0)
            {
                _model = EF.article.SingleOrDefault(x => x.ID == model.ID);
                if (_model == null)
                    return Result.Fail("文章错误");
                if (_model.MemberID != MemberID)
                    return Result.Fail("权限不足");

                _model = EF.article.Attach(_model);
            }

            _model.Audit = (int)EnumHelper.AuditType.待审核;
            _model.AuditReason = string.Empty;
            _model.ClassifyID = model.ClassifyID;
            _model.Content = model.Content;
            _model.Img = model.Img;
            _model.IsReply = model.IsReply;
            _model.Password = model.Password;
            _model.Remark = model.Remark;
            _model.Source = model.Source;
            _model.SourceUrl = model.SourceUrl;
            _model.SpecialID = model.SpecialID;
            _model.Title = model.Title;

            if (LoginMember.IsProve.Value)
            {
                _model.Audit = (int)EnumHelper.AuditType.审核通过;
            }

            bool isSucc = false;
            if (model.ID > 0)
            {
                isSucc = EF.SaveChanges() > 0;
            }
            else
            {
                EF.article.Add(_model);
                isSucc = EF.SaveChanges() > 0;
            }

            string msg = "执行失败";
            if (!string.IsNullOrWhiteSpace(resJson))
            {
                var resList = JsonConvert.DeserializeObject<List<resource>>(resJson);
                resList.ForEach(x =>
                {
                    x.CreateTime = DateTime.Now;
                    x.ArticleID = _model.ID;
                });

                using (var context = new Model.QunProjectEntities())
                {
                    using (var dbContextTransaction = context.Database.BeginTransaction())
                    {
                        try
                        {
                            context.Database.ExecuteSqlCommand("delete from resource where ArticleID = @ArticleID", new MySql.Data.MySqlClient.MySqlParameter("@ArticleID", model.ID));
                            context.resource.AddRange(resList);
                            context.SaveChanges();
                            dbContextTransaction.Commit();
                            isSucc = true;
                        }
                        catch (Exception e)
                        {
                            dbContextTransaction.Rollback();
                            msg = e.Message;
                            isSucc = false;
                        }
                    }
                }
            }

            return isSucc ? Result.Success() : Result.Fail(msg);
        }

        public Result UserEditSpecialResult(Model.special model)
        {
            model.Content = model.Content.UnicodeToString();
            //model.Content = model.Content.Replace("[ad]", "+");
            //model.Content = model.Content.Replace("[eq]", "=");
            //model.Content = HttpUtility.UrlDecode(model.Content);

            if (model.Name.IsNullOrWhiteSpace())
                return Result.Fail("专题名称不能为空");
            if (model.Content.IsNullOrWhiteSpace())
                return Result.Fail("专题内容不能为空");

            var _model = new Model.special()
            {
                ClickAmount = 0,
                Content = string.Empty,
                CreateTime = DateTime.Now,
                Img = string.Empty,
                MemberID = MemberID,
                IsValid = true,
                Name = string.Empty,
                Remark = string.Empty
            };

            if (model.ID > 0)
            {
                _model = EF.special.SingleOrDefault(x => x.ID == model.ID);
                if (_model == null)
                    return Result.Fail("专题错误");
                if (_model.MemberID != MemberID)
                    return Result.Fail("权限不足");

                _model = EF.special.Attach(_model);
            }

            _model.Img = model.Img;
            _model.Name = model.Name;
            _model.Remark = model.Remark;
            _model.Content = model.Content;

            bool isSucc = false;
            if (model.ID > 0)
            {
                isSucc = EF.SaveChanges() > 0;
            }
            else
            {
                EF.special.Add(_model);
                isSucc = EF.SaveChanges() > 0;
            }
            return isSucc ? Result.Success() : Result.Fail();
        }

        public Result UserEditPasswordResult(string pwd = "", string pwd1 = "", string pwd2 = "")
        {
            if (!Common.Verify.VerifyLength(pwd, 6, 18))
                return Result.Fail("旧密码长度[6]至[18]个字符");
            if (!Common.Verify.VerifyLength(pwd1, 6, 18))
                return Result.Fail("新密码长度[6]至[18]个字符");
            if (!Common.Verify.VerifyLength(pwd2, 6, 18))
                return Result.Fail("重复密码长度[6]至[18]个字符");
            if (pwd1 != pwd2)
                return Result.Fail("两次输入密码不一致");

            var pwdMD5 = Common.Security.MD5Encrypt32(pwd);
            var pwd1MD5 = Common.Security.MD5Encrypt32(pwd1);
            if (LoginMember.Password == pwdMD5)
            {
                var member = EF.member.SingleOrDefault(x => x.ID == LoginMember.ID);
                member = EF.member.Attach(member);
                member.Password = pwd1MD5;
                LoginMember.Password = pwd1MD5;

                bool isSucc = EF.SaveChanges() > 0;
                return isSucc ? Result.Success() : Result.Fail();
            }
            else
            {
                return Result.Fail("旧密码错误");
            }
        }

        public Result GetMemberArticleListResult(int page = 1, int limit = 10)
        {
            var list = (from a in EF.article
                        join m in EF.member on a.MemberID equals m.ID
                        where a.Types == (int)EnumHelper.ArticleType.普通文章 && a.IsValid.Value && a.MemberID == MemberID
                        orderby a.CreateTime descending
                        select new
                        {
                            a.ID,
                            a.CreateTime,
                            a.Title,
                            a.MemberID,
                            a.Audit,
                            a.AuditReason,
                            a.ClickAmount,
                            a.Password,
                            a.Img,
                            a.Praise,
                            a.Content,
                            a.Criticism,
                            a.Tops,
                            a.IsReply,
                            a.Types,
                            a.ClassifyID,
                            a.SpecialID,
                            a.Sort,
                            UserName = m.Name
                        });

            List<classify> classifyList = EF.classify.Where(x => true).ToList();
            List<special> specialList = EF.special.Where(x => x.MemberID == LoginMember.ID).ToList();

            var data = list.Skip((page - 1) * limit).Take(limit).ToList().Select(x => new
            {
                x.ID,
                CreateTime = x.CreateTime.Value.ToString("yyyy-MM-dd hh:mm:ss"),
                x.Title,
                x.MemberID,
                x.ClickAmount,
                x.Img,
                x.Praise,
                Content = HttpHelper.ReplaceHtmlTag(x.Content, 72),
                x.Criticism,
                x.Tops,
                x.Audit,
                x.AuditReason,
                x.IsReply,
                x.Types,
                x.ClassifyID,
                x.SpecialID,
                SpecialName = new Func<string>(() =>
                {
                    if (x.SpecialID == null)
                        return "";
                    else
                        return specialList.SingleOrDefault(c => c.ID == x.SpecialID).Name;
                }).Invoke(),
                x.Sort,
                x.UserName,
                ClassifyName = new Func<string>(() =>
                {
                    var _name = string.Empty;
                    var _classify = classifyList.SingleOrDefault(s => s.ID == x.ClassifyID);
                    if (_classify != null)
                    {
                        _name = _classify.Name;
                    }
                    return _name;
                }).Invoke()
            });
            return Result.SuccessReturnData(list.Count(), data);
        }

        public Result GetMemberSpecialListResult(int page = 1, int limit = 10)
        {
            var list = from s in EF.special
                       join m in EF.member on s.MemberID equals m.ID
                       orderby s.CreateTime descending
                       where s.MemberID == MemberID && s.IsValid.Value
                       select new
                       {
                           s.ID,
                           s.CreateTime,
                           s.Remark,
                           s.Img,
                           s.Name,
                           s.Content,
                           s.ClickAmount,
                           s.MemberID,
                           m.Phone,
                           UserName = m.Name,
                           m.Number
                       };
            var data = list.Skip((page - 1) * limit).Take(limit).ToList().Select(x => new
            {
                x.ID,
                CreateTime = x.CreateTime.Value.ToString("yyyy-MM-dd hh:mm:ss"),
                x.Remark,
                x.Img,
                x.Name,
                Content = HttpHelper.ReplaceHtmlTag(x.Content, 25),
                x.ClickAmount,
                x.MemberID,
                x.Phone,
                x.UserName,
                x.Number
            });
            return Result.SuccessReturnData(list.Count(), data);
        }

        public Result GetMemberDiscussListResult(int page = 1, int limit = 10)
        {
            var list = (from a in EF.article
                        join m in EF.member on a.MemberID equals m.ID
                        where a.Types == (int)EnumHelper.ArticleType.技术讨论 && a.IsValid.Value && a.MemberID == MemberID
                        orderby a.CreateTime descending, a.Tops
                        select new
                        {
                            a.ID,
                            a.CreateTime,
                            a.Title,
                            a.MemberID,
                            a.Audit,
                            a.AuditReason,
                            a.ClickAmount,
                            a.Password,
                            a.Img,
                            a.Praise,
                            a.Content,
                            a.Criticism,
                            a.Tops,
                            a.IsReply,
                            a.Types,
                            a.ClassifyID,
                            a.SpecialID,
                            a.Sort,
                            UserName = m.Name
                        });

            var data = list.Skip((page - 1) * limit).Take(limit).ToList().Select(x => new
            {
                x.ID,
                CreateTime = x.CreateTime.Value.ToString("yyyy-MM-dd hh:mm:ss"),
                x.Title,
                x.MemberID,
                x.ClickAmount,
                x.Img,
                x.Praise,
                x.Audit,
                x.AuditReason,
                Content = HttpHelper.ReplaceHtmlTag(x.Content, 222),
                x.Criticism,
                x.Tops,
                x.IsReply,
                x.Types,
                x.ClassifyID,
                x.SpecialID,
                x.Sort,
                x.UserName
            });
            return Result.SuccessReturnData(list.Count(), data);
        }

        public Result GetMemberIndexResult()
        {
            var articleCount = EF.article.Where(x => x.MemberID == MemberID && x.IsValid.Value && x.Types == (int)EnumHelper.ArticleType.普通文章).Count();
            var discussCount = EF.article.Where(x => x.MemberID == MemberID && x.IsValid.Value && x.Types == (int)EnumHelper.ArticleType.技术讨论).Count();
            var specialCount = EF.special.Where(x => x.MemberID == MemberID).Count();
            var replyCount = EF.reply.Where(x => x.MemberID == MemberID).Count();
            var data = new { articleCount, discussCount, specialCount, replyCount };
            return Result.Success(data);
        }

        public Result GetHotSpecialResult()
        {
            var data = Cache.Get(CacheName.GetHotSpecialResult_Cache);
            if (data == null)
            {
                data = (from s in EF.special
                        join m in EF.member on s.MemberID equals m.ID
                        orderby s.ClickAmount descending
                        select new
                        {
                            s.ID,
                            s.CreateTime,
                            s.Remark,
                            s.Img,
                            s.Name,
                            s.Content,
                            s.ClickAmount,
                            s.MemberID,
                            m.Phone,
                            UserName = m.Name,
                            m.Number
                        }).Take(5).ToList().Select(x => new
                        {
                            x.ID,
                            CreateTime = x.CreateTime.Value.ToString("yyyy-MM-dd hh:mm:ss"),
                            x.Remark,
                            x.Img,
                            x.Name,
                            Content = HttpHelper.ReplaceHtmlTag(x.Content, 50),
                            x.ClickAmount,
                            x.MemberID,
                            x.Phone,
                            x.UserName,
                            x.Number
                        });
                Cache.Set(CacheName.GetHotSpecialResult_Cache, data, 120);
            }
            return Result.Success(data);
        }

        public Result GetSpecialArticleListResult(int specialId, int page = 1, int limit = 10)
        {
            var special = EF.special.SingleOrDefault(x => x.ID == specialId);
            if (special == null)
                return Result.Fail("不存在此专题");

            special = EF.special.Attach(special);
            special.ClickAmount += 1;
            EF.SaveChanges();

            var list = (from a in EF.article
                        join m in EF.member on a.MemberID equals m.ID
                        where a.Types == (int)EnumHelper.ArticleType.普通文章 && a.Audit == (int)EnumHelper.AuditType.审核通过 && a.SpecialID == specialId
                        orderby a.CreateTime ascending
                        select new
                        {
                            a.ID,
                            a.CreateTime,
                            a.Title,
                            a.MemberID,
                            a.Audit,
                            a.AuditReason,
                            a.ClickAmount,
                            a.Password,
                            a.Img,
                            a.Praise,
                            a.Content,
                            a.Criticism,
                            a.Tops,
                            a.IsReply,
                            a.Types,
                            a.ClassifyID,
                            a.SpecialID,
                            a.Sort,
                            UserName = m.Name,
                            m.Number
                        });

            List<classify> classifyList = EF.classify.Where(x => true).ToList();

            var data = list.Skip((page - 1) * limit).Take(limit).ToList().Select(x => new
            {
                x.ID,
                CreateTime = x.CreateTime.Value.ToString("yyyy-MM-dd hh:mm:ss"),
                x.Title,
                x.MemberID,
                x.ClickAmount,
                x.Img,
                x.Praise,
                Content = HttpHelper.ReplaceHtmlTag(x.Content, 72),
                x.Criticism,
                x.Tops,
                x.IsReply,
                x.Types,
                x.SpecialID,
                x.Sort,
                x.UserName,
                x.Number
            });
            var result = new { data, special };
            return Result.SuccessReturnData(list.Count(), result);
        }

        public Result GetSpecialListResult(int page = 1, int limit = 10)
        {
            var list = from s in EF.special
                       join m in EF.member on s.MemberID equals m.ID
                       orderby s.CreateTime descending
                       select new
                       {
                           s.ID,
                           s.CreateTime,
                           s.Remark,
                           s.Img,
                           s.Name,
                           s.Content,
                           s.ClickAmount,
                           s.MemberID,
                           m.Phone,
                           UserName = m.Name,
                           m.Number
                       };
            var data = list.Skip((page - 1) * limit).Take(limit).ToList().Select(x => new
            {
                x.ID,
                CreateTime = x.CreateTime.Value.ToString("yyyy-MM-dd hh:mm:ss"),
                x.Remark,
                x.Img,
                x.Name,
                Content = HttpHelper.ReplaceHtmlTag(x.Content, 50),
                x.ClickAmount,
                x.MemberID,
                x.Phone,
                x.UserName,
                x.Number
            });
            return Result.SuccessReturnData(list.Count(), data);
        }

        public Result GetDiscussListResult(int page = 1, int limit = 10)
        {
            var list = (from a in EF.article
                        join m in EF.member on a.MemberID equals m.ID
                        where a.Types == (int)EnumHelper.ArticleType.技术讨论 && a.IsValid.Value && a.Audit == (int)EnumHelper.AuditType.审核通过
                        orderby a.CreateTime descending, a.Tops
                        select new
                        {
                            a.ID,
                            a.CreateTime,
                            a.Title,
                            a.MemberID,
                            a.Audit,
                            a.AuditReason,
                            a.ClickAmount,
                            a.Password,
                            a.Img,
                            a.Praise,
                            a.Content,
                            a.Criticism,
                            a.Tops,
                            a.IsReply,
                            a.Types,
                            a.ClassifyID,
                            a.SpecialID,
                            a.Sort,
                            UserName = m.Name,
                            m.Number
                        });

            var data = list.Skip((page - 1) * limit).Take(limit).ToList().Select(x => new
            {
                x.ID,
                CreateTime = x.CreateTime.Value.ToString("yyyy-MM-dd hh:mm:ss"),
                x.Title,
                x.MemberID,
                x.ClickAmount,
                x.Img,
                x.Praise,
                Content = new Func<object>(() =>
                {
                    if (x.Password.IsNullOrWhiteSpace())
                        return HttpHelper.ReplaceHtmlTag(x.Content, 72);
                    else
                        return "此文章内容已加密";
                }).Invoke(),
                x.Criticism,
                x.Tops,
                x.IsReply,
                x.Types,
                x.ClassifyID,
                x.SpecialID,
                x.Sort,
                x.UserName,
                x.Number
            });
            return Result.SuccessReturnData(list.Count(), data);
        }

        public Result GetArticleResult(int articleId, string password = "")
        {
            var article = EF.article.SingleOrDefault(x => x.ID == articleId);
            if (article == null)
                return Result.Fail("找不到此文章");
            if (!article.IsValid.Value)
                return Result.Fail("此文章已失效");
            if (article.Audit != (int)Model.EnumHelper.AuditType.审核通过)
                return Result.Fail("此文章审核错误");

            var Self = false;
            if (IsLogin())
            {
                if (LoginMember.ID == article.MemberID)
                {
                    Self = true;
                }
            }

            if (!string.IsNullOrWhiteSpace(article.Password) && !Self)
            {
                if (string.IsNullOrWhiteSpace(password))
                    return Result.Fail("此文章已加密，请输入密码");
                else
                {
                    if (article.Password != password)
                    {
                        return Result.Fail("文章密码错误");
                    }
                }
            }

            article = EF.article.Attach(article);
            article.ClickAmount++;
            EF.SaveChanges();

            var model = (from a in EF.article
                         join m in EF.member on a.MemberID equals m.ID
                         where a.ID == articleId
                         orderby a.CreateTime descending
                         select new
                         {
                             a.ID,
                             a.CreateTime,
                             a.Remark,
                             a.Title,
                             a.Content,
                             a.MemberID,
                             a.Audit,
                             a.AuditReason,
                             a.Source,
                             a.SourceUrl,
                             a.ClickAmount,
                             a.Password,
                             a.Img,
                             a.Praise,
                             a.Criticism,
                             a.Tops,
                             a.IsReply,
                             a.Types,
                             a.ClassifyID,
                             a.SpecialID,
                             a.Sort,
                             a.IsValid,
                             UserName = m.Name,
                             m.Number
                         }).SingleOrDefault();
            if (model != null)
            {
                var data = new
                {
                    model.ID,
                    CreateTime = model.CreateTime.Value.ToString("yyyy-MM-dd hh:mm:ss"),
                    model.Title,
                    model.MemberID,
                    model.ClickAmount,
                    model.Praise,
                    model.Source,
                    model.SourceUrl,
                    model.Content,
                    model.Img,
                    model.Criticism,
                    model.Tops,
                    model.IsReply,
                    model.Types,
                    model.ClassifyID,
                    model.SpecialID,
                    model.Sort,
                    model.UserName,
                    model.Number,
                    DescContent = HttpHelper.ReplaceHtmlTag(model.Content, 72),
                    Resources = new Func<object>(() =>
                    {
                        return EF.resource.Where(r => r.ArticleID == model.ID);
                    }).Invoke()
                };
                return Result.Success(data);
            }
            else
            {
                var data = new
                {
                    article.ID,
                    CreateTime = article.CreateTime.Value.ToString("yyyy-MM-dd hh:mm:ss"),
                    article.Title,
                    article.MemberID,
                    article.ClickAmount,
                    article.Praise,
                    article.Source,
                    article.SourceUrl,
                    article.Content,
                    article.Img,
                    article.Criticism,
                    article.Tops,
                    article.IsReply,
                    article.Types,
                    article.ClassifyID,
                    article.SpecialID,
                    article.Sort,
                    Number = "",
                    DescContent = HttpHelper.ReplaceHtmlTag(article.Content, 72),
                    UserName = "系统管理员",
                    Resources = ""
                };
                return Result.Success(data);
            }
        }

        public Result GetArticleSeoResult(int articleId)
        {
            var article = EF.article.SingleOrDefault(x => x.ID == articleId);
            if (article == null)
                return Result.Fail("找不到此文章");
            if (!article.IsValid.Value)
                return Result.Fail("此文章已失效");
            if (article.Audit != (int)Model.EnumHelper.AuditType.审核通过)
                return Result.Fail("此文章审核错误");

            var model = EF.article.SingleOrDefault(x => x.ID == articleId);
            var data = new
            {
                model.ID,
                model.Title,
                Content = HttpHelper.ReplaceHtmlTag(model.Content, 72)
            };
            return Result.Success(data);
        }

        public Result GetArticleListResult(int? classifyId, int page = 1, int limit = 10)
        {
            var list = (from a in EF.article
                        join m in EF.member on a.MemberID equals m.ID
                        where a.Types == (int)EnumHelper.ArticleType.普通文章 && a.IsValid.Value && a.Audit == (int)EnumHelper.AuditType.审核通过
                        orderby a.CreateTime descending, a.ClickAmount descending, a.Tops
                        select new
                        {
                            a.ID,
                            a.CreateTime,
                            a.Title,
                            a.MemberID,
                            a.Audit,
                            a.AuditReason,
                            a.ClickAmount,
                            a.Password,
                            a.Img,
                            a.Praise,
                            a.Content,
                            a.Criticism,
                            a.Tops,
                            a.IsReply,
                            a.Types,
                            a.ClassifyID,
                            a.SpecialID,
                            a.Sort,
                            UserName = m.Name,
                            m.Number
                        });

            classify classify = null;
            List<classify> classifyList = null;
            if (classifyId.HasValue)
            {
                classify = EF.classify.SingleOrDefault(x => x.ID == classifyId);
            }
            if (classify == null)
            {
                classifyList = EF.classify.Where(x => true).ToList();
                classify = new classify
                {
                    CreateTime = DateTime.Now,
                    ID = 0,
                    Name = "所有分类",
                    Types = (int)EnumHelper.ClassifyType.普通分类,
                    Remark = string.Empty
                };
            }
            else
            {
                list = list.Where(x => x.ClassifyID == classifyId);
            }
            var data = list.Skip((page - 1) * limit).Take(limit).ToList().Select(x => new
            {
                x.ID,
                CreateTime = x.CreateTime.Value.ToString("yyyy-MM-dd hh:mm:ss"),
                x.Title,
                x.MemberID,
                x.ClickAmount,
                x.Img,
                x.Praise,
                Content = new Func<object>(() =>
                {
                    if (x.Password.IsNullOrWhiteSpace())
                        return HttpHelper.ReplaceHtmlTag(x.Content, 72);
                    else
                        return "此文章内容已加密";
                }).Invoke(),
                x.Criticism,
                x.Tops,
                x.IsReply,
                x.Types,
                x.ClassifyID,
                x.SpecialID,
                x.Sort,
                x.UserName,
                x.Number,
                ClassifyName = new Func<string>(() =>
                {
                    var _name = string.Empty;
                    if (classify.ID == 0)
                    {
                        var _classify = classifyList.SingleOrDefault(s => s.ID == x.ClassifyID);
                        if (_classify != null)
                        {
                            _name = _classify.Name;
                        }
                    }
                    else
                    {
                        _name = classify.Name;
                    }
                    return _name;
                }).Invoke()
            });
            var result = new { data, classify };
            return Result.SuccessReturnData(list.Count(), result);
        }

        public Result GetClassifyResult()
        {
            var list = EF.classify.Where(x => true);
            return Result.Success(list);
        }

        public Result GetFriendHrefResult()
        {
            var data = Cache.Get(CacheName.GetFriendHrefResult_Cache);
            if (data == null)
            {
                data = EF.article.Where(x => x.Types == (int)EnumHelper.ArticleType.友情链接 && x.IsValid.Value && x.Audit == (int)EnumHelper.AuditType.审核通过).OrderByDescending(x => x.Sort).ToList().Select(x => new
                {
                    x.SourceUrl,
                    x.Source,
                    x.Sort
                });
                Cache.Set(CacheName.GetFriendHrefResult_Cache, data, 120);
            }
            return Result.Success(data);
        }

        public Result GetHomeIndexResult()
        {
            var data = Cache.Get(CacheName.GetHomeIndexResult_Cache);
            if (data == null)
            {
                var classifyList = EF.classify.Where(x => true);
                var newProclaim = EF.article.Where(x => x.Types == (int)EnumHelper.ArticleType.网站公告 && x.IsValid.Value && x.Audit == (int)EnumHelper.AuditType.审核通过).OrderByDescending(x => x.CreateTime).Take(6).ToList().Select(x => new
                {
                    x.ID,
                    CreateTime = x.CreateTime.Value.ToString("yyyy-MM-dd hh:mm:ss"),
                    x.Title,
                    x.MemberID,
                    x.Audit,
                    x.AuditReason,
                    x.ClickAmount,
                    x.Password,
                    x.Img,
                    x.Praise,
                    Content = new Func<object>(() =>
                    {
                        if (x.Password.IsNullOrWhiteSpace())
                            return HttpHelper.ReplaceHtmlTag(x.Content, 72);
                        else
                            return "此文章内容已加密";
                    }).Invoke(),
                    x.Criticism,
                    x.Tops,
                    x.IsReply,
                    x.Types,
                    x.ClassifyID,
                    x.SpecialID,
                    x.Sort
                });
                var Banner = EF.article.Where(x => x.Types == (int)EnumHelper.ArticleType.幻灯片 && x.IsValid.Value && x.Audit == (int)EnumHelper.AuditType.审核通过).OrderByDescending(x => x.CreateTime).Take(5).ToList().Select(x => new
                {
                    x.ID,
                    CreateTime = x.CreateTime.Value.ToString("yyyy-MM-dd hh:mm:ss"),
                    x.Title,
                    x.MemberID,
                    x.Audit,
                    x.AuditReason,
                    x.ClickAmount,
                    x.Password,
                    x.Img,
                    x.SourceUrl,
                    x.Praise,
                    x.Criticism,
                    x.Tops,
                    x.IsReply,
                    x.Types,
                    x.ClassifyID,
                    x.SpecialID,
                    x.Sort
                });
                var newArticle = (from a in EF.article
                                  join m in EF.member on a.MemberID equals m.ID
                                  where a.Types == (int)EnumHelper.ArticleType.普通文章 && a.IsValid.Value && a.Audit == (int)EnumHelper.AuditType.审核通过
                                  orderby a.CreateTime descending, a.ClickAmount descending, a.Tops
                                  select new
                                  {
                                      a.ID,
                                      a.CreateTime,
                                      a.Title,
                                      a.MemberID,
                                      a.Audit,
                                      a.AuditReason,
                                      a.ClickAmount,
                                      a.Password,
                                      a.Img,
                                      a.Praise,
                                      a.Content,
                                      a.Criticism,
                                      a.Tops,
                                      a.IsReply,
                                      a.Types,
                                      a.ClassifyID,
                                      a.SpecialID,
                                      a.Sort,
                                      UserName = m.Name,
                                      m.Number
                                  }).Take(10).ToList().Select(x => new
                                  {
                                      x.ID,
                                      CreateTime = x.CreateTime.Value.ToString("yyyy-MM-dd hh:mm:ss"),
                                      x.Title,
                                      x.MemberID,
                                      x.Audit,
                                      x.AuditReason,
                                      x.ClickAmount,
                                      x.Password,
                                      x.Img,
                                      x.Praise,
                                      Content = new Func<object>(() =>
                                      {
                                          if (x.Password.IsNullOrWhiteSpace())
                                              return HttpHelper.ReplaceHtmlTag(x.Content, 72);
                                          else
                                              return "此文章内容已加密";
                                      }).Invoke(),
                                      x.Criticism,
                                      x.Tops,
                                      x.IsReply,
                                      x.Types,
                                      x.ClassifyID,
                                      x.SpecialID,
                                      x.Sort,
                                      x.UserName,
                                      x.Number,
                                      ClassifyName = new Func<string>(() =>
                                      {
                                          var _name = string.Empty;
                                          var _classify = classifyList.SingleOrDefault(s => s.ID == x.ClassifyID);
                                          if (_classify != null)
                                          {
                                              _name = _classify.Name;
                                          }
                                          return _name;
                                      }).Invoke()
                                  });
                data = new { newProclaim, Banner, newArticle };
                Cache.Set(CacheName.GetHomeIndexResult_Cache, data, 120);
            }
            return Result.Success(data);
        }

        public Result GetHotDiscussResult()
        {
            var data = Cache.Get(CacheName.GetHotDiscussResult_Cache);
            if (data == null)
            {
                data = EF.article.Where(x => x.Types == (int)EnumHelper.ArticleType.技术讨论 && x.IsValid.Value && x.Audit == (int)EnumHelper.AuditType.审核通过).OrderByDescending(x => x.CreateTime).OrderByDescending(x => x.ClickAmount).OrderBy(x => x.Tops).Take(6).ToList().Select(x => new
                {
                    x.ID,
                    CreateTime = x.CreateTime.Value.ToString("yyyy-MM-dd hh:mm:ss"),
                    x.Title,
                    x.MemberID,
                    x.Audit,
                    x.AuditReason,
                    x.ClickAmount,
                    x.Password,
                    x.Img,
                    x.Praise,
                    x.Criticism,
                    Content = new Func<object>(() =>
                    {
                        if (x.Password.IsNullOrWhiteSpace())
                            return HttpHelper.ReplaceHtmlTag(x.Content, 50);
                        else
                            return "此文章内容已加密";
                    }).Invoke(),
                    x.Tops,
                    x.IsReply,
                    x.Types,
                    x.ClassifyID,
                    x.SpecialID,
                    x.Sort
                });
                Cache.Set(CacheName.GetHotDiscussResult_Cache, data, 120);
            }
            return Result.Success(data);
        }

        public Result GetHotArticleResult()
        {
            var data = Cache.Get(CacheName.GetHotArtucleResult_Cache);
            if (data == null)
            {
                data = EF.article.Where(x => x.Types == (int)EnumHelper.ArticleType.普通文章 && x.IsValid.Value && x.Audit == (int)EnumHelper.AuditType.审核通过).OrderByDescending(x => x.CreateTime).OrderByDescending(x => x.ClickAmount).OrderBy(x => x.Tops).Take(6).ToList().Select(x => new
                {
                    x.ID,
                    CreateTime = x.CreateTime.Value.ToString("yyyy-MM-dd hh:mm:ss"),
                    x.Title,
                    x.MemberID,
                    x.Audit,
                    x.AuditReason,
                    x.ClickAmount,
                    x.Password,
                    x.Img,
                    x.Praise,
                    x.Criticism,
                    Content = new Func<object>(() =>
                    {
                        if (x.Password.IsNullOrWhiteSpace())
                            return HttpHelper.ReplaceHtmlTag(x.Content, 50);
                        else
                            return "此文章内容已加密";
                    }).Invoke(),
                    x.Tops,
                    x.IsReply,
                    x.Types,
                    x.ClassifyID,
                    x.SpecialID,
                    x.Sort
                });
                Cache.Set(CacheName.GetHotArtucleResult_Cache, data, 120);
            }
            return Result.Success(data);
        }

        public Result SendSmsResult(string phone, string code, int? type)
        {
            if (!Common.Verify.IsPhone(phone))
                return Result.Fail("手机号码格式错误");
            if (code.IsNullOrWhiteSpace())
                return Result.Fail("验证码不能为空");

            if (type.HasValue)
            {
                if (type == (int)EnumHelper.SmsType.注册)
                {
                    var _model = EF.member.SingleOrDefault(x => x.Phone == phone);
                    if (_model != null)
                        return Result.Fail("已存在此用户");
                }
                if (type == (int)EnumHelper.SmsType.找回密码)
                {
                    var _model = EF.member.SingleOrDefault(x => x.Phone == phone);
                    if (_model == null)
                        return Result.Fail("不存在此用户");
                }
            }

            bool isCache = Cache.Set(phone, code, 10);
            bool isSucc = false;
            if (isCache)
            {
                string result = Sms.SendSms(phone, code);
                dynamic obj = JsonConvert.DeserializeObject(result);
                if (obj.status == 0)
                    isSucc = true;
            }
            return isSucc ? Result.Success() : Result.Fail();
        }

        public Result FileUpload(int type = (int)FileHelper.FileTypes.不限制, string base64 = "")
        {
            if (!base64.IsNullOrWhiteSpace())
            {
                FileHelper.FileUpload file = new FileHelper.FileUpload(FileHelper.FileTypes.图片);
                file.DomainUrl = "";
                string data = file.Base64(base64);
                if (!data.IsNullOrWhiteSpace())
                    return Result.Success(data);
                else
                    return Result.Fail(file.ErrorMag);
            }
            else
            {
                if (System.Web.HttpContext.Current.Request.Files.Count > 0)
                {
                    FileHelper.FileUpload file = new FileHelper.FileUpload((FileHelper.FileTypes)Enum.Parse(typeof(FileHelper.FileTypes), type.ToString()));
                    file.DomainUrl = "";
                    string data = string.Empty;
                    for (int i = 0; i < System.Web.HttpContext.Current.Request.Files.Count; i++)
                    {
                        data += file.HttpPosted(System.Web.HttpContext.Current.Request.Files[i]) + ',';
                    }
                    data = data.TrimEnd(new[] { ',' });

                    if (!data.IsNullOrWhiteSpace())
                        return Result.Success(data);
                    else
                        return Result.Fail(file.ErrorMag);
                }
                else
                {
                    return Result.Fail("文件数量为0");
                }
            }
        }

        public Result UserEditInfoResult(member model)
        {
            var _member = LoginMember;
            if (!Common.Verify.VerifyLength(model.Name, 2, 10))
                return Result.Fail("用户名长度[2]至[10]个字符");

            _member = EF.member.Attach(_member);
            _member.Name = model.Name;
            _member.Img = model.Img;
            _member.Identity = model.Identity;
            _member.Introduce = model.Introduce;

            bool isSucc = EF.SaveChanges() > 0;
            return isSucc ? Result.Success() : Result.Fail();
        }

        public Result UserInsertResult(string phone, string passWord, string smsCode)
        {
            if (!Common.Verify.IsPhone(phone))
                return Result.Fail("手机号码格式错误");
            if (!Common.Verify.VerifyLength(passWord, 6, 18))
                return Result.Fail("密码长度[6]至[18]个字符");
            if (!Common.Verify.IsNumber(smsCode))
                return Result.Fail("短信验证码格式错误");

            var member = EF.member.SingleOrDefault(x => x.Phone == phone);
            if (member != null)
                return Result.Fail("已经存在此用户");
            var cacheCode = Cache.Get(phone);
            if (cacheCode == null)
                return Result.Fail("未获取验证码");
            if (cacheCode.ToString() != smsCode)
                return Result.Fail("验证码错误");

            string _number = Common.RanString.RandomNumber(8);
            while (EF.member.SingleOrDefault(x => x.Number == _number) != null)
                _number = Common.RanString.RandomNumber(8);

            member = new member()
            {
                BanReason = string.Empty,
                BanTime = null,
                CreateTime = DateTime.Now,
                Identity = string.Empty,
                Img = string.Empty,
                IsAdmin = false,
                Name = "用户" + _number,
                Number = _number,
                IsProve = false,
                Password = Common.Security.MD5Encrypt32(passWord),
                Remark = string.Empty,
                Introduce = string.Empty,
                Phone = phone,
                States = (int)EnumHelper.MemberStates.正常
            };

            EF.member.Add(member);
            bool isSucc = EF.SaveChanges() > 0;
            Cache.Clear(phone);
            return isSucc ? Result.Success() : Result.Fail();
        }

        public Result UserBackPasswordResult(string phone, string passWord, string smsCode)
        {
            if (!Common.Verify.IsPhone(phone))
                return Result.Fail("手机号码格式错误");
            if (!Common.Verify.VerifyLength(passWord, 6, 18))
                return Result.Fail("密码长度[6]至[18]个字符");
            if (!Common.Verify.IsNumber(smsCode))
                return Result.Fail("短信验证码格式错误");

            var member = EF.member.SingleOrDefault(x => x.Phone == phone);
            if (member == null)
                return Result.Fail("不存在此用户");
            var cacheCode = Cache.Get(phone);
            if (cacheCode == null)
                return Result.Fail("未获取验证码");
            if (cacheCode.ToString() != smsCode)
                return Result.Fail("验证码错误");

            member = EF.member.Attach(member);
            member.Password = Common.Security.MD5Encrypt32(passWord);

            bool isSucc = EF.SaveChanges() > 0;
            Cache.Clear(phone);
            return isSucc ? Result.Success() : Result.Fail();
        }

        public Result UserLoginResult(string phone, string passWord = "", string smsCode = "")
        {
            if (!Common.Verify.IsPhone(phone))
                return Result.Fail("手机号码格式错误");
            if (smsCode.IsNullOrWhiteSpace() && passWord.IsNullOrWhiteSpace())
                return Result.Fail("请输入密码");
            if (!Common.Verify.VerifyLength(passWord, 6, 18) && smsCode.IsNullOrWhiteSpace())
                return Result.Fail("密码长度[6]至[18]个字符");
            if (!Common.Verify.IsNumber(smsCode) && passWord.IsNullOrWhiteSpace())
                return Result.Fail("短信验证码格式错误");

            var member = EF.member.SingleOrDefault(x => x.Phone == phone);
            if (member == null)
                return Result.Fail("用户名或密码错误");

            string token = Common.RanString.RandomLetter(32);
            if (!passWord.IsNullOrWhiteSpace())
            {
                var passwordMD5 = Common.Security.MD5Encrypt32(passWord);
                if (member.Password == passwordMD5)
                {
                    bool isSucc = Cache.Set(token, member, 1440);
                    return isSucc ? Result.Success(token) : Result.Fail("登录失败");
                }
                else
                {
                    return Result.Fail("用户名或密码错误");
                }
            }
            else
            {
                var code = Cache.Get(phone);
                if (code == null)
                    return Result.Fail("请获取短信验证码");

                if (code.ToString() == smsCode)
                {
                    bool isSucc = Cache.Set(token, member, 1440);
                    return isSucc ? Result.Success(token) : Result.Fail("登录失败");
                }
                else
                {
                    return Result.Fail("短信验证码错误");
                }
            }
        }

        public Result UserLoginInfoResult()
        {
            return Result.Success(LoginMember);
        }

        public Result ClearCache()
        {
            Type type = typeof(CacheName);
            var fields = type.GetFields();
            foreach (var item in fields)
            {
                Cache.Clear(item.Name);
            }
            return Result.Success();
        }
    }
}
